package com.cqyc.network.utils

import android.content.Context
import android.net.Uri
import android.util.Log
import java.util.regex.Pattern


class Utils {
    companion object {
        fun getAppVersionName(context: Context): String {
            var versionName = ""
            try {
                val pm = context.packageManager
                val pi = pm.getPackageInfo(context.packageName, 0)
                versionName = pi.versionName
                if (versionName == null || versionName.isEmpty()) {
                    return ""
                }
            } catch (e: Exception) {
                Log.e("VersionInfo", "Exception", e)
            }
            return versionName
        }

        fun getAppVersionCode(context: Context): Int {
            var versionCode = 0
            try {
                val pm = context.packageManager
                val pi = pm.getPackageInfo(context.packageName, 0)
                versionCode = pi.versionCode
            } catch (e: Exception) {
                Log.e("VersionInfo", "Exception", e)
            }
            return versionCode
        }

        fun buildUrl(url: String, paramsMap: Map<String, String>?): String {
            val requestUrl = url.replace("/#/", "ZXZXZXXAXAXAXDDDD")
            val uri = Uri.parse(requestUrl)
            val builder = uri.buildUpon()
            if (paramsMap != null && paramsMap.isNotEmpty()) {
                paramsMap.forEach {
                    builder.appendQueryParameter(it.key, it.value)
                }
            }
            return builder.toString().replace("ZXZXZXXAXAXAXDDDD", "/#/")
        }

        //region 正则 从 URI 获取值或键值对
        /**
         * 获取url中的指定的key对应的值
         *
         * @param key 指定的key
         * @return key对应的值
         */
        fun getValueFromUrl(url: String?, key: String?): String? {
            return getParams(url)[key]
        }

        fun getParams(url: String?): Map<String?, String?> {
            val regEx = "(\\?|&+)(.+?)=([^&]*)" //匹配参数名和参数值的正则表达式
            val p = Pattern.compile(regEx)
            val m = p.matcher(url)
            // LinkedHashMap是有序的Map集合，遍历时会按照加入的顺序遍历输出
            val paramMap: MutableMap<String?, String?> = LinkedHashMap()
            while (m.find()) {
                val paramName = m.group(2) //获取参数名
                val paramVal = m.group(3) //获取参数值
                paramMap[paramName] = paramVal
            }
            return paramMap
        }
    }
}